package edu.hnu.tradeserver.controller;

import edu.hnu.commonutils.EnumResultCode;
import edu.hnu.commonutils.Result;
import edu.hnu.commonutils.model.User;
import edu.hnu.tradeserver.auth.JwtOperator;
import edu.hnu.tradeserver.entity.Trades;
import edu.hnu.tradeserver.entity.Transaction;
import edu.hnu.tradeserver.service.TransactionService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import java.util.List;

import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
//@CrossOrigin(origins = "*")
@RequestMapping("/transaction")
@Api(value = "transaction接口",tags = {"transaction"})
public class TransactionController {
    @Autowired
    TransactionService transactionService;

    @Autowired
    JwtOperator jwtOperator;
    private User parseToken(String token){
        Claims claims = jwtOperator.getClaimsFromToken(token);
        User user = new User(-1L,-2,false);
        try {
            Long id = Long.parseLong(claims.get("id").toString());
            int userType= Integer.parseInt(claims.get("user_type").toString());
            if (userType != 1) {
                // 判断是否是不是生产商
                user.setAuthorized(false);
            }else {
                user.setUserType(userType);
                user.setId(id);
                user.setAuthorized(true);
            }
        } catch (NumberFormatException e) {
            user.setAuthorized(false);
            return user;
        }
        return user;
    }
    @GetMapping("/transactionInfo")
    @ApiOperation(value = "hca'xun",notes = "")
    public Result<Transaction> transactionInfo(@RequestHeader("token") String token,@ApiParam(value = "时间范围") @RequestParam("timeRange") String timeRange,
        @RequestParam(value = "sortOrder", defaultValue = "asc") String sortOrder,
        @RequestParam(value = "sortBy", defaultValue = "Date") String sortBy){
        System.out.println(token);
        User user = parseToken(token);
        if(!user.isAuthorized()){
            return Result.error(EnumResultCode.UNAUTHORIZED);
        }
        System.out.println(user);




        List<Transaction> transactionList = transactionService.getTransactionInfoByCondition(timeRange, sortOrder, sortBy);
        return Result.ok().data(transactionList);
    }
//    public Result transactionInfo(){
//        return transactionService.transactionInfo();
//    }
}
